import 'package:bt_dsp_88/model/model_extension.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import '../../model/model.dart';
import '../bluetooth/send_data.dart';
import '../notify/globalState.dart';
import 'model_default.dart';

///专门处理蓝牙指令，与通道本身的数据，两者的转换
extension ChannelModelExtension on ChannelModel {
  ///把本身的数据，转换成指令字符串，每条指令，用“｜”分割
  String get data {
    String str = '';

    ///通道频率，Q值，增益
    for (var sign in sign_list) {
      NotifyData data = NotifyData(key: 'EQ', message: '${this.num}', body: sign);
      List<int> bytes = SendData.getBytes(data);
      str += bytes.toHexstr();
      str += '|';
    }

    ///高通
    NotifyData data_high = NotifyData(key: 'FILTER', message: '${this.num}', body: high_pass!);
    List<int> bytes_high = SendData.getBytes(data_high);
    str += bytes_high.toHexstr();
    str += '|';

    ///低通
    NotifyData data_low = NotifyData(key: 'FILTER', message: '${this.num}', body: low_pass!);
    List<int> bytes_low = SendData.getBytes(data_low);
    str += bytes_low.toHexstr();
    str += '|';

    ///音量
    NotifyData data_db = NotifyData(key: 'DB', body: this);
    List<int> bytes_db = SendData.getBytes(data_db);
    str += bytes_db.toHexstr();
    str += '|';

    ///正反相
    NotifyData data_phase = NotifyData(key: 'PHASE', body: this);
    List<int> bytes_phase = SendData.getBytes(data_phase);
    str += bytes_phase.toHexstr();
    str += '|';

    ///通道延时
    NotifyData data_delay = NotifyData(key: 'DELAY', body: this);
    List<int> bytes_delay = SendData.getBytes(data_delay);
    str += bytes_delay.toHexstr();
    str += '|';

    ///合频
    NotifyData data_sum = NotifyData(key: 'SUM', body: this);
    List<int> bytes_sum = SendData.getBytes(data_sum);
    str += bytes_sum.toHexstr();
    str += '|';

    return str;
  }

  ///根据指令，转换成通道相应的数据
  void dataToModel(List<int> bytes) {
    if (bytes.length != 14 && bytes.length != 20) {
      return;
    }
    if (bytes.length == 14 && bytes[0] != 0xAA && bytes[1] != 0x55) {
      return;
    }
    if (bytes.length == 20 && bytes[0] != 0xAA && bytes[1] != 0x00 && bytes[1] != 0x01) {
      return;
    }

    ///筛选出真实有用的数据
    List<int> data = [];
    if (bytes.length == 14) {
      data = bytes.sublist(2, bytes.length);
    } else {
      data = bytes.sublist(3, bytes.length - 3);
    }

    ///1字节的cmd
    int cmd_1 = data[0];
    int num_1 = data[1];
    List<int> data_1 = data.sublist(2, data.length);
    int cmd_3 = data.sublist(0, 3).decimal;
    int num_3 = data[3];
    List<int> data_3 = data.sublist(4, data.length);

    ///混音
    if (cmd_3 == ble_sum) {
      toSum(data_3);
    } else {
      switch (cmd_1) {
        //eq
        case ble_eq:
        case ble_eq_unit:
          toEq(data_1);
        case ble_phase:
          toPhase(data_1);
        case ble_delay:
          toDelay(data_1);
        case ble_mute:
          toDb(data_1);
        case ble_high:
        case ble_low:
          toCross(data_1, cmd_1);
          break;
        default:
      }
    }
  }

  ///字节转换成通道混音数据
  void toSum(List<int> data) {
    List<int> list = data.asMap().entries.map(($0) => $0.value == 0 ? 0 : $0.key + 1).toList();

    input_list.clear();
    input_list.addAll(list);
    input_custom_list.clear();
    input_custom_list.addAll(list);
  }

  ///字节转换成eq
  void toEq(List<int> data) {
    int index = data[0];
    SignModel sign = sign_list[index];
    sign.freq = data.sublist(1, 3).decimal;
    sign.Q = data.sublist(3, 5).decimal / 100.0;
    sign.gain = data.sublist(5, 7).decimal / 10.0 - 20.0;
  }

  ///字节转换成正反相
  void toPhase(List<int> data) {
    phase = data[0] == 0;
  }

  ///字节转换成延迟
  void toDelay(List<int> data) {
    delay = ((data.sublist(0, 2).decimal / 100.0).roundDouble(1)).toString();
    delay_type = 'ms';
  }

  ///字节转换成静音，音量
  void toDb(List<int> data) {
    mute = data[0] == 1;
    int v = data.sublist(1, 3).decimal;
    db = (v == 0 ? 0 : v / -10).toInt();
  }

  ///字节转换成分频器
  void toCross(List<int> data, int cmd) {
    var filter = cmd == ble_high ? high_pass : low_pass;
    if (filter == null) return;
    int type = data[0];
    int slope = data[1];
    switch (type) {
      case 0x00:
        filter.type!.name = 'Bessel';
      case 0x01:
        filter.type!.name = 'Butter-W';
      case 0x02:
        filter.type!.name = 'Link-R';
      default:
        break;
    }

    switch (slope) {
      case 0x00:
        filter.type?.slope = 6;
      case 0x01:
        filter.type?.slope = 12;
      case 0x02:
        filter.type?.slope = 24;
      case 0x03:
        filter.type?.slope = 36;
      case 0x04:
        filter.type?.slope = 48;
      default:
        break;
    }
    filter.freq = data.sublist(2, 4).decimal;
  }

  ///整个channel，所有数据一次性发送
  void sendToDevice({required bool containSum}) {
    List<String> array = data.split('|');
    if (containSum == false) {
      var str = 'AA55${ble_sum.bytes.toHexstr()}';
      array.removeWhere(($0) => $0.contains(str));
    }
    _update(0, 'UPDATE', array);
  }

  ///发送数据到设备
  void _update(int index, String tag, List<String> array) {
    if (index == 0) {
      EasyLoading.show(status: 'Waiting...', dismissOnTap: false);
    }
    if (index < array.length) {
      globalState.state = NotifyData(key: tag, body: array[index]);
      Future.delayed(const Duration(milliseconds: 10), () {
        _update(index + 1, tag, array);
      });
    } else {
      globalState.state = NotifyData(key: '全部刷新');
      Future.delayed(const Duration(seconds: 2), () {
        EasyLoading.showSuccess('Successfully!', duration: const Duration(milliseconds: 1000));
      });
    }
  }
}

extension GlobalModelExtension on GlobalModel {
  ///所有通道上的设置，转换成 数据
  void getData() {
    String str = '';
    for (var ch in ch_list) {
      str += ch.data;
    }

    ///总音量
    NotifyData data = NotifyData(key: 'MUTE_ALL', body: null);
    List<int> bytes = SendData.getBytes(data);
    str += bytes.toHexstr();

    this.data = str;
  }

  ///整个数据加载到本地，和设备端
  void sendToDevice({required String tag}) {
    ///重置reset设备
    if (tag == 'RESET_DSP') {
      globalModel.reset();
      globalState.state = NotifyData(key: tag, body: null);
      globalState.state = NotifyData(key: '全部刷新');
      EasyLoading.show(status: 'Resetting...', dismissOnTap: false);
      Future.delayed(const Duration(seconds: 2), () {
        EasyLoading.dismiss();
        EasyLoading.showSuccess('Successfully!', duration: const Duration(milliseconds: 1000));
      });
    }

    ///同步本地数据到设备
    else if (tag == 'UPDATE') {
      List<String> array = globalModel.data.split('|');
      _update(0, tag, array);
    }
  }

  ///发送数据到设备
  void _update(int index, String tag, List<String> array) {
    if (index == 0) {
      EasyLoading.show(status: 'Loading...', dismissOnTap: false);
    }
    if (index < array.length) {
      globalState.state = NotifyData(key: tag, body: array[index]);
      Future.delayed(const Duration(milliseconds: 10), () {
        _update(index + 1, tag, array);
      });
    } else {
      globalState.state = NotifyData(key: '全部刷新');
      EasyLoading.showSuccess('Successfully!', duration: const Duration(milliseconds: 1000));
    }
  }
}

///upload，从硬件拿到数据，赋值到本地通道上
extension GlobalModelExtension2 on GlobalModel {
  ///根据字节信息，找到对应的通道
  ChannelModel? toChannel(List<int> bytes) {
    if (bytes.length != 14 && bytes.length != 20) {
      return null;
    }
    bool isBle = bytes.length == 20;
    int num_1 = isBle ? bytes[4] : bytes[3];
    int cmd_3 = isBle ? bytes.sublist(3, 6).decimal : bytes.sublist(2, 5).decimal;
    int num_3 = isBle ? bytes[6] : bytes[5];
    int num = cmd_3 == ble_sum ? num_3 : num_1;
    return num == 0 || num - 0xC0 - 1 > 7 ? null : ch_list[num - 0xC0 - 1];
  }

  ///从设备拿到数据，转换成通道的值
  void dataToModel(List<List<int>> list) {
    // if (list.length != 308 && list.length != 297) {
    //   return;
    // }

    for (var bytes in list) {
      int cmd = bytes.length == 20 ? bytes[3] : bytes[2];

      ///通道总音量
      if (cmd == ble_mute_all) {
        List<int> data = bytes.length == 20 ? bytes.sublist(4, bytes.length - 3) : bytes.sublist(3, bytes.length);
        mute = data[0] == 1;
        db = (data.sublist(1, 3).decimal == 0 ? 0 : data.sublist(1, 3).decimal / -10).toInt();
      } else {
        ChannelModel? ch = toChannel(bytes);
        if (ch != null) {
          ch.dataToModel(bytes);
        }
      }
    }

    ///数据处理完，根据输出通道的选中什么样的输入通道，判断当前是什么模式
    ///1，重置输出模式
    input_type = '';
    List<int> sum_list = [];
    for (var ch in ch_list) {
      int sum = ch.input_list.reduce((a, b) => a + b);
      sum_list.add(sum);
    }
    int sum_total = sum_list.reduce((a, b) => a + b);
    if (sum_total == 0) {
      input_type = '';
    } else if (sum_total == 36 &&
        sum_list[0] == 1 &&
        sum_list[1] == 2 &&
        sum_list[2] == 3 &&
        sum_list[3] == 4 &&
        sum_list[4] == 5 &&
        sum_list[5] == 6 &&
        sum_list[6] == 7 &&
        sum_list[7] == 8) {
      input_type = 'Assign';
    } else {
      input_type = 'Custom';
    }
  }
}
